/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.distribution.comment.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.distribution.comment.Enums.DistributionUserIncomeStateEnum;
import com.yami.shop.distribution.comment.dao.DistributionUserIncomeMapper;
import com.yami.shop.distribution.comment.dao.DistributionUserWalletMapper;
import com.yami.shop.distribution.comment.dto.DistributionOrderDto;
import com.yami.shop.distribution.comment.dto.DistributionUserIncomeDto;
import com.yami.shop.distribution.comment.dto.DistributionUserIncomeOrderDto;
import com.yami.shop.distribution.comment.dto.StatisticsDisUserIncomeDto;
import com.yami.shop.distribution.comment.model.DistributionUserIncome;
import com.yami.shop.distribution.comment.model.DistributionUserWallet;
import com.yami.shop.distribution.comment.model.DistributionUserWalletBill;
import com.yami.shop.distribution.comment.param.RangeTimeParam;
import com.yami.shop.distribution.comment.service.DistributionUserIncomeService;
import com.yami.shop.distribution.comment.service.DistributionUserWalletBillService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lgh on 2019/04/01.
 */
@Service
@AllArgsConstructor
public class DistributionUserIncomeServiceImpl extends ServiceImpl<DistributionUserIncomeMapper, DistributionUserIncome> implements DistributionUserIncomeService {

    private final DistributionUserIncomeMapper distributionUserIncomeMapper;

    private final DistributionUserWalletMapper distributionUserWalletMapper;

    private final DistributionUserWalletBillService distributionUserWalletBillService;


    @Override
    public IPage<DistributionUserIncome> incomeAndDistributionUserPage(Page page, Long shopId, RangeTimeParam rangeTimeParam, String userMobile, String orderNumber, Integer state) {
        return distributionUserIncomeMapper.incomeAndDistributionUserPage(page, shopId, rangeTimeParam, userMobile, orderNumber,state);
    }

    @Override
    public IPage<DistributionOrderDto> getDistributionOrderDtoByDistributionUserId(Page page, Long distributionUserId) {
        return distributionUserIncomeMapper.getDistributionOrderDtoByDistributionUserId(page, distributionUserId);
    }

    @Override
    public StatisticsDisUserIncomeDto statisticsDistributionUserIncome(Long distributionUserId) {
        StatisticsDisUserIncomeDto statisticsDisUserIncomeDto = new StatisticsDisUserIncomeDto();
        Date now = new Date();
        double todayAmount = distributionUserIncomeMapper.statisticsDisUserIncome(distributionUserId, DateUtil.beginOfDay(now), DateUtil.endOfDay(now));
        double monthAmount = distributionUserIncomeMapper.statisticsDisUserIncome(distributionUserId, DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now));
        statisticsDisUserIncomeDto.setTodayAmount(todayAmount);
        statisticsDisUserIncomeDto.setMonthAmount(monthAmount);
        return statisticsDisUserIncomeDto;
    }

    @Override
    public IPage<DistributionUserIncomeDto> getDistributionUserIncomePage(PageParam<DistributionUserIncome> page, Long distributionUserId) {
        return distributionUserIncomeMapper.getDistributionUserIncomePage(page, distributionUserId);
    }

    @Override
    public IPage<DistributionUserIncomeOrderDto> getMyPromotionOrderByState(PageParam<DistributionUserIncomeOrderDto> page, Long distributionUserId, Integer state) {
        return distributionUserIncomeMapper.getMyPromotionOrderByState(page, distributionUserId, state, I18nMessage.getDbLang());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void commissionSettlementHandle(Date date) {
        // 查询需要处理的支付收入记录,15天前确认收货的订单
        List<DistributionUserIncome> distributionUserIncomeList = distributionUserIncomeMapper.listWaitCommissionSettlement(date);
        List<DistributionUserIncome> updateBatchDistributionUserIncomeList = new ArrayList<>();
        List<DistributionUserWalletBill> saveBatchDistributionWalletBillList = new ArrayList<>();

        for (DistributionUserIncome distributionUserIncome : distributionUserIncomeList) {
            // 减少用户的待结算佣金，添加已结算金额
            DistributionUserWallet distributionUserWallet = distributionUserWalletMapper.selectById(distributionUserIncome.getWalletId());
            if (distributionUserWallet == null) {
                // 未找到分销员信息
                throw new YamiShopBindException("yami.distribution.exist.error");
            }

            // 添加分销钱包日志
            distributionUserWallet.setSettledAmount(Arith.add(distributionUserWallet.getSettledAmount(), distributionUserIncome.getIncomeAmount()));
            distributionUserWallet.setUnsettledAmount(Arith.sub(distributionUserWallet.getUnsettledAmount(), distributionUserIncome.getIncomeAmount()));
            distributionUserWallet.setAddupAmount(Arith.add(distributionUserWallet.getAddupAmount(), distributionUserIncome.getIncomeAmount()));
            distributionUserWalletMapper.updateById(distributionUserWallet);

            // 更新收入状态
            updateBatchDistributionUserIncomeList.add(distributionUserIncome);

            // 添加钱包变动日志
            saveBatchDistributionWalletBillList.add(new DistributionUserWalletBill(distributionUserWallet, "佣金结算", -distributionUserIncome.getIncomeAmount(), distributionUserIncome.getIncomeAmount(), 0.0, distributionUserIncome.getIncomeAmount(), 0));
        }
        // 批量更新分销收入状态
        if (CollectionUtils.isNotEmpty(updateBatchDistributionUserIncomeList)) {
            if (distributionUserIncomeMapper.updateBatchState(updateBatchDistributionUserIncomeList, DistributionUserIncomeStateEnum.COMMISSION.getValue()) <= 0) {
                // 批量更新分销收入状态失败
                throw new YamiShopBindException("yami.distribution.batch.update.income");
            }
        }

        // 批量添加钱包变动日志
        if (CollectionUtils.isNotEmpty(saveBatchDistributionWalletBillList)) {
            distributionUserWalletBillService.saveBatch(saveBatchDistributionWalletBillList);
        }
    }

}
